﻿
using System;
namespace CID.Tests.Support.Configuration.Database
{
    public class Initializer
    {
        private bool databaseSetup = false;
        private SnapshotHandler snapshotHandler = new SnapshotHandler(TestsConfiguration.DatabaseConnectionString, TestsConfiguration.DatabaseInitializationConfiguration.IsLocalDatabase);

        public void Initialize(Action SetupData)
        {
            if (!databaseSetup)
            {
                SetupDatabase();
                SetupData();
                snapshotHandler.TakeSnapshot();
                databaseSetup = true;
            }
            snapshotHandler.RollbackToSnapshot();
        }

        private void SetupDatabase()
        {
            var scriptProvider = new ScriptProvider(TestsConfiguration.DatabaseInitializationConfiguration.DatabaseScriptsBasePath);
            var scriptExecuter = new ScriptExecuter(TestsConfiguration.DatabaseConnectionString, TestsConfiguration.DatabaseInitializationConfiguration.InitializationVariables.GetVariableValue);

            foreach (var scriptPath in scriptProvider.GetScriptList())
                scriptExecuter.Execute(scriptPath);
        }
    }
}
